package com.hong.taotaomall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hong.taotaomall.dto.GoodsDto;
import com.hong.taotaomall.entity.District;
import com.hong.taotaomall.entity.Result;
import com.hong.taotaomall.service.IDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 地区表 前端控制器
 * </p>
 *
 * @author hong
 * @since 2023-03-25
 */
@RestController
@RequestMapping("/district")
public class DistrictController {

    @Autowired
    private IDistrictService districtService;

    @Autowired
    private RedisTemplate  redisTemplate;

//    @GetMapping("/{name}")
//    public Result<String> getCodeByName(@PathVariable String name){
//        String code = districtService.getOne(new LambdaQueryWrapper<District>().eq(District::getName, name)).getCode();
//        return Result.success();
//    }

    @GetMapping("/list/{parent}")
    public Result<List<District>> getDistrict(@PathVariable String parent) {
        List<District> provinceList = null;
        String key = "province" + "_" + parent;
        provinceList = (List<District>) redisTemplate.opsForValue().get(key);
        if(provinceList != null){
            return Result.success(provinceList);
        }

        provinceList =  districtService.list(new LambdaQueryWrapper<District>().eq(District::getParent, parent));
        for (int i = 0; i < provinceList.size(); i++) {
            District parentProvince = provinceList.get(i);
            List<District> cityList = districtService.list(new LambdaQueryWrapper<District>().eq(District::getParent, parentProvince.getCode()));
            for (int j = 0; j < cityList.size(); j++) {
                District parentCity = cityList.get(j);
                List<District> districtList = districtService.list(new LambdaQueryWrapper<District>().eq(District::getParent, parentCity.getCode()));
                parentCity.setChildren(districtList);
            }
            parentProvince.setChildren(cityList);
        }
        redisTemplate.opsForValue().set(key, provinceList);
        return Result.success(provinceList);
    }

}
